package cn.xtits.xtf.common.utils;

import java.io.*;

/**
 * Created by HaiL on 2017/7/3.
 */
public class FileUtil {


    public static final byte[] inputStream2byte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    public static byte[] object2byte(Object obj) throws IOException {
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            bytes = byteArrayOutputStream.toByteArray();

        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {

                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {

                }
            }

        }
        return bytes;
    }

    public static String saveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
        String filePath = path + "/" + filename;

        FileOutputStream fs = new FileOutputStream(filePath);
        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
        return filePath;
    }

    public static String saveFileFromInputStream(InputStream stream, String filename) throws IOException {
        File directory = new File("");//设定为当前文件夹
        String path = directory.getCanonicalPath();
        return saveFileFromInputStream(stream, path, filename);

    }

    public static String saveFile(byte[] byteStr, String path, String fileName) throws IOException {
        String filePath = path + "/" + fileName;
        InputStream stream = new ByteArrayInputStream(byteStr);
        return  saveFileFromInputStream(stream,path,fileName);
    }

    public static String saveFile(byte[] byteStr, String fileName) throws IOException {

        InputStream stream = new ByteArrayInputStream(byteStr);
        return saveFileFromInputStream(stream, fileName);
    }
}
